Welcome to Deploying a Highly Available Docker Swarm Cluster on Multiple VPS Nodes. As your application grows beyond a single server, you need container orchestration. Docker Swarm offers a simpler, native alternative to Kubernetes for orchestrating containers across multiple VPS nodes.
1. The Architecture of a Swarm
A Docker Swarm consists of Manager nodes and Worker nodes. Managers handle cluster management tasks, maintain the cluster state, and schedule services. Workers simply receive and execute tasks from the Managers. For true high availability, you need at least three Manager nodes (to maintain quorum) distributed across different physical availability zones.
2. Preparing the Nodes
Before initializing the swarm, ensure all VPS nodes have Docker installed and can communicate with each other over a private network. You must open specific ports in your firewall: TCP 2377 (cluster management), TCP/UDP 7946 (node communication), and UDP 4789 (overlay network traffic).
3. Initializing the Swarm
SSH into the VPS you want to be your primary manager. Run docker swarm init --advertise-addr <PRIVATE_IP>. Docker will output a command containing a join token. This token is used to securely add other nodes to your cluster.
4. Adding Manager and Worker Nodes
To add workers, SSH into your worker VPS instances and paste the join command generated in the previous step. To add more managers (highly recommended for fault tolerance), run docker swarm join-token manager on the primary manager, then paste that specific output on the new manager nodes.
5. Deploying a Service Across the Swarm
Instead of running individual containers, you deploy "Services" to a Swarm. A service defines the image to run and the desired state. For example, docker service create --replicas 5 --name my-web nginx tells the Swarm manager to ensure exactly 5 instances of Nginx are running, distributed optimally across the available nodes.
6. The Power of the Routing Mesh
Swarm's routing mesh allows you to publish a service on a port, and the Swarm will route traffic to an active container regardless of which node receives the request. If you hit port 80 on Node A, but the container is only running on Node B, the routing mesh seamlessly forwards the traffic.
Conclusion
Docker Swarm provides a robust, highly available infrastructure for your containers with a significantly lower learning curve than Kubernetes, making it ideal for managing distributed applications across multiple VPS instances.